//import angular core
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

//import third package
import 'rxjs/add/operator/switchMap';

//import service
import { HeroService } from '../../service/hero.service';
import { UserService } from '../../service/user.service';

//import class
import { Hero } from '../../domain/hero';
import { User } from '../../domain/user';

@Component({
  selector: 'hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css'],
  providers: [HeroService, UserService]
})
export class HeroDetailComponent implements OnInit {

  hero: Hero;
  user: User;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private heroService: HeroService,
    private userService: UserService,
    private location: Location) { }

  ngOnInit(): void {
    this.route.params
      .switchMap((params: Params) => this.heroService.getHeroById(+params['id']))
      .subscribe(hero => {
        this.hero = hero;
        this.userService.getUserById(hero.ownerId)
        .then(user => this.user = user);
      });
      this.userService.getUserById(<number><any>localStorage.getItem('userId'))
      .then(user => this.user = user);
  }
  goBack(): void {
    this.location.back();
  }
  rent(): void {
    if(this.hero.ownerId ==0){ //车未被租用
    this.hero.ownerId = this.user.id;
    this.user.money = this.user.money - this.hero.price;
    this.heroService.updateHero(this.hero);
    this.userService.updateUser(this.user);
    alert("租车成功");
    }else{
      alert("汽车已经被租用了");
    }
  }
}
